package co.yixiang;

import co.yixiang.annotation.AnonymousAccess;
import co.yixiang.utils.SpringContextHolder;
import com.binarywang.spring.starter.wxjava.miniapp.config.WxMaAutoConfiguration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
// import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;

/**
 * 启动类
 * 启用异步任务、RESTful控制器、Spring Boot应用、事务管理以及MyBatis的Mapper扫描
 */
@EnableAsync
@RestController
@SpringBootApplication(exclude = {WxMaAutoConfiguration.class})
@EnableTransactionManagement
@MapperScan(basePackages ={"co.yixiang.modules.*.service.mapper", "co.yixiang.config"})
public class AppRun {

    public static void main(String[] args) {
        SpringApplication.run(AppRun.class, args);
        System.out.println("电商系统管理后台启动成功...");
    }

    /**
     * 创建SpringContextHolder实例
     * 用于在Spring上下文中存储和获取对象
     * @return SpringContextHolder实例
     */
    @Bean
    public SpringContextHolder springContextHolder() {
        return new SpringContextHolder();
    }

    /**
     * 配置Tomcat服务器
     * 添加对特殊字符的处理
     * @return 配置好的ServletWebServerFactory实例
     */
    // @Bean
    // public ServletWebServerFactory webServerFactory() {
    //     TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory();
    //     fa.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
    //     return fa;
    // }
    /**
     * 优化Undertow服务器配置
     */
    @Bean
    public WebServerFactoryCustomizer<UndertowServletWebServerFactory> undertowCustomizer() {
        return factory -> {
            // 设置WebSocket缓冲池
            factory.addDeploymentInfoCustomizers(deploymentInfo -> {
                WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
                webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 1024));
                deploymentInfo.addServletContextAttribute(
                    WebSocketDeploymentInfo.ATTRIBUTE_NAME, 
                    webSocketDeploymentInfo
                );
            });

            // 根据系统内存情况决定是否使用直接内存
            boolean useDirectBuffers = Runtime.getRuntime().maxMemory() > 1024 * 1024 * 1024;
            factory.setUseDirectBuffers(useDirectBuffers);

            // 设置IO线程数和工作线程数
            int ioThreads = Runtime.getRuntime().availableProcessors();
            factory.setIoThreads(ioThreads);
            factory.setWorkerThreads(ioThreads * 8);

            // 设置缓冲区大小
            factory.setBufferSize(useDirectBuffers ? 1024 * 16 : 1024 * 8);
        };
    }

    /**
     * 访问首页提示
     * @return /
     */
    @GetMapping("/")
    @AnonymousAccess
    public String index() {
        return "Backend service started successfully";
    }
}
